package com.shjy.signdemo;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    private static final String SD_CARD_TEMP_PHOTO_PATH = "/sdcard/fdajdtemp.jpg";

    public static final int SUBMIT_DONE = 1;
    public static final int FDAIDL_DONE = 2;
    public static final int MSG_EXCUTE_RESULT = 666;

    private static Handler viewHandler = null;

    private WebView mWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
//
//        mWebView = (WebView) findViewById(R.id.webview);
//        mWebView.getSettings().setJavaScriptEnabled(true);
//
//        mWebView.addJavascriptInterface(new Delegate(), "delegate");
//        mWebView.loadUrl("file:///android_asset/index.html");


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mWebView = (WebView) findViewById(R.id.webview);

        viewHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Log.e(TAG, "Message received:"+msg.what);

                if(msg.what == SUBMIT_DONE){
                    Bundle data = msg.getData();
                    String rtn = data.getString("rtn");
                    onSubmitDone(rtn);
                }
            }
        };

        // 优先使用缓存
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
        mWebView.getSettings().setDomStorageEnabled(true);

        mWebView.setWebChromeClient(new MainWebChromeClient());
        mWebView.setWebViewClient(new MainWebViewClient());
        mWebView.addJavascriptInterface(new Delegate(), "delegate");

        // 默认加载首页
        mWebView.loadUrl("file:///android_asset/index.html");
    }

    @Override
    public boolean onKeyDown(int keyCode ,KeyEvent keyEvent){
        if(keyCode==keyEvent.KEYCODE_BACK){
            if(mWebView.canGoBack()){
                mWebView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, keyEvent);

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) { //resultCode为回传的标记，我在B中回传的是RESULT_OK
            case RESULT_OK:
                Bundle b=data.getExtras(); //data为B中回传的Intent
                String str=b.getString("imgpath");//str即为回传的值
                saveImage(str,true);
                break;
            default:
                break;
        }
    }

    public void saveImage(final String image,final boolean showMessage){
    	/*final ProgressDialog dialog = ProgressDialog.show(context, context.getResources().getString(
				R.string.doing), context.getResources().getString(
						R.string.submitting), true,true);*/


        new Thread() {
            public void run() {
                try {

                    Map<String, String> params = new HashMap<String, String>();
                    Map<String, File> files = new HashMap<String, File>();
                    if(image != null && image.length()>0){
                        File f = new File("/mnt/sdcard/", image);

                        files.put("myphoto.jpg", f);
                    }

                    String rtn = post("http://218.202.254.248/JDFDAGISAPP" + "/upload", params, files);

                    //String rtn = HttpFileUpTool.upload(AppConfig.REPORT_HOST + "/upload", file);
                    JSONObject jsonObject = new JSONObject(rtn);
                    Message msg = new Message();
                    msg.what = MainActivity.SUBMIT_DONE;

                    Bundle data = new Bundle();
                    data.putString("rtn", "http://218.202.254.248/JDFDAGISAPP/"+(jsonObject.get("result")!=null?jsonObject.get("result").toString():""));
                    data.putBoolean("msg", showMessage);
                    data.putInt("cid", 1);
                    data.putInt("rid", 1);
                    msg.setData(data);
                    String str1="imgpath";
                    Intent mIntent = new Intent();
                    mIntent.putExtra(str1, "http://218.202.254.248/JDFDAGISAPP/"+(jsonObject.get("result")!=null?jsonObject.get("result").toString():""));

                    viewHandler.sendMessage(msg);

                } catch (Exception e) {
                    e.printStackTrace();

                    Message msg = new Message();
                    msg.what = MainActivity.SUBMIT_DONE;

                    Bundle data = new Bundle();
                    data.putString("rtn", "{'success': 'false'}");
                    data.putBoolean("msg", showMessage);
                    data.putInt("cid", 1);
                    data.putInt("rid", 1);
                    msg.setData(data);
                    viewHandler.sendMessage(msg);

                } finally {

                }
            }
        }.start();
    }

    public static String post(String actionUrl, Map<String, String> params,
                              Map<String, File> files) throws IOException {

        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String PREFIX = "--", LINEND = "\r\n";
        String MULTIPART_FROM_DATA = "multipart/form-data";
        String CHARSET = "UTF-8";
        StringBuilder sb2 = new StringBuilder();

        URL uri = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
        conn.setReadTimeout(30 * 1000);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("connection", "keep-alive");
        //conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
                + ";boundary=" + BOUNDARY);


        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINEND);
            sb.append("Content-Disposition: form-data; name=\""
                    + entry.getKey() + "\"" + LINEND);
            sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
            sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
            sb.append(LINEND);
            sb.append(entry.getValue());
            sb.append(LINEND);
        }

        DataOutputStream outStream = new DataOutputStream(conn
                .getOutputStream());
        outStream.write(sb.toString().getBytes());
        InputStream in = null;

        if (files != null){
            for (Map.Entry<String, File> file : files.entrySet()) {
                StringBuilder sb1 = new StringBuilder();
                sb1.append(PREFIX);
                sb1.append(BOUNDARY);
                sb1.append(LINEND);
                sb1
                        .append("Content-Disposition: form-data; name=\"img\"; filename=\""
                                + file.getKey() + "\"" + LINEND);
                //sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
                sb1.append("Content-Type: image/png" + LINEND);
                sb1.append(LINEND);
                outStream.write(sb1.toString().getBytes());

                InputStream is = new FileInputStream(file.getValue());
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = is.read(buffer)) != -1) {
                    outStream.write(buffer, 0, len);
                }

                is.close();
                outStream.write(LINEND.getBytes());
            }
            try{
                byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
                outStream.write(end_data);
                outStream.flush();


                int res = conn.getResponseCode();
                //if (res == 200) {
                in = conn.getInputStream();
//					int ch;
//
//					while ((ch = in.read()) != -1) {
//						sb2.append((char) ch);
//					}
                BufferedReader br = new BufferedReader(new InputStreamReader(in,"utf-8"));
                String line = "";

                for (line = br.readLine(); line != null; line = br.readLine()) {
                    sb2.append(line);
                }
                //}
                outStream.close();
                conn.disconnect();
            }catch(Exception ex){
                ex.printStackTrace();
            }
        }
        return sb2.toString();
    }

    private void onSubmitDone( String rtn){
        try{
            mWebView.loadUrl("javascript:submitDone('"+rtn+"')");
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }

    class Delegate extends Object {

        @JavascriptInterface
        public void addSign() {
            Intent intent=new Intent();
            intent.setClass(MainActivity.this, Main2Activity.class);
            Bundle bundle=new Bundle();
            String str1="aaaaaa";
            bundle.putString("str1", str1);
            intent.putExtras(bundle);
            startActivityForResult(intent, 0);//这里采用startActivityForResult来做跳转，此处的0为一个依据，可以写其他的值，但一定要>=0
            //startActivity(new Intent(MainActivity.this, Main2Activity.class));
        }

        @JavascriptInterface
        public void sign() {
            startActivity(new Intent(MainActivity.this, Main3Activity.class));
        }

        @JavascriptInterface
        public void upload() {
            SharedPreferences sharedPreferences = getSharedPreferences("sign", Context.MODE_PRIVATE);
            String imageUrl = sharedPreferences.getString("imageUrl", "");
        }
    }

    class MainWebViewClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (url.indexOf("login.html") != -1) {
                mWebView.stopLoading();
            } else {
                super.onPageStarted(view, url, favicon);
            }
        }
    }

    class MainWebChromeClient extends WebChromeClient {

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(view.getContext());
            builder.setTitle(null).setMessage(message).setPositiveButton("确定", null);
            builder.setCancelable(false);
            AlertDialog dialog = builder.create();
            dialog.show();
            result.confirm();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }
    }
}